<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="employeeSearch" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="employeeSearch.ename" placeholder="员工姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="employeeSearch.addr" placeholder="员工住址"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="employeeSearch.did" placeholder="所在部门">
            <el-option label="所有部门" value="0"></el-option>
            <el-option :label="d.dname" :value="d.did" v-for="d in departmentList" :key="d.did"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addEmployee">添加员工</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="employeeList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="工号"
            align="center"
            prop="eid"
            width="180"/>
        <el-table-column
            label="姓名"
            prop="ename"
            align="center"/>
        <el-table-column
            label="性别"
            prop="sex"
            align="center"/>
        <el-table-column
            label="年龄"
            prop="age"
            align="center"/>
        <el-table-column
            label="住址"
            prop="addr"
            align="center"/>
        <el-table-column
            label="所在部门"
            prop="dname"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页导航面板-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      {{ employee }}
      <el-form :model="employee" :rules="rules" ref="ruleForm">
        <el-form-item label="员工姓名" prop="ename" :label-width="formLabelWidth">
          <el-input v-model="employee.ename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工性别" prop="sex" :label-width="formLabelWidth">
          <el-radio v-model="employee.sex" label="男">男</el-radio>
          <el-radio v-model="employee.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="员工年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="employee.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="家庭住址" prop="addr" :label-width="formLabelWidth">
          <el-input v-model="employee.addr" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="所在部门" prop="cid" :label-width="formLabelWidth">
          <el-select v-model="employee.did" placeholder="请选择所在部门">
            <el-option label="所有部门" value="0"></el-option>
            <el-option :label="d.dname" :value="d.did" v-for="d in departmentList" :key="d.did"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveemployee">保 存</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import employeeApi from "@/api/employee"
import departmentApi from "@/api/department"

export default {
  data() {
    let checkAge = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('年龄不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('年龄必须为数字值'))
      } else if (value < 1 || value > 200) {
        return callback(new Error('年龄必须在1-200之间'))
      } else {
        callback()
      }
    }


    return {
      employeeList: [],
      page: 1,
      pageSize: 5,
      total: 100,
      employeeSearch: {},
      departmentList: [],
      dialogFormVisible: false,
      employee: {},
      title: '添加员工',
      formLabelWidth: '100px',
      multipleSelection: [],
      eids: [],

      rules: {

        ename: [
          {required: true, message: '请输入员工姓名', trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
        age: [
          {validator: checkAge, trigger: 'blur'}
        ],
        addr: [
          {required: true, message: '请输入员工住址', trigger: 'blur'},
        ],
        cid: [
          {required: true, message: '请选择员工班级', trigger: 'blur'},
        ]
      }
    }
  }
  ,
  created() {
    this.search()
    this.findAllDepartments()
  },
  methods: {
    async findAllDepartments() {
        const {data: res} = await departmentApi.findAllDepartments()
      console.log(res)
      if (res.code === 200) {
        this.departmentList = res.data.list
      }
    },
    async search() {
      const {data: res} = await employeeApi.search(this.page, this.pageSize, this.employeeSearch)
      console.log(res)
      if (res.code === 200) {
        this.employeeList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    addEmployee() {
      this.title = "添加员工"
      this.employee = {}
      this.dialogFormVisible = true
    },
    saveemployee() {
      this.$refs.ruleForm.validate(async valid => {
        let url = "/employee/add"
        let method = "post"
        if (this.employee.eid) {
          url = "/employee/update"
          method = "put"
        }
        if (valid) {
          const {data: res} = await employeeApi.save(url, method, this.employee)
          console.log("res:", res)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {
                this.dialogFormVisible = false
                this.search()
              }
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.search()
      console.log(`每页 ${val} 条`);
    },

    handleCurrentChange(val) {
      this.page = val
      this.search()
      console.log(`当前页: ${val}`);
    },

    handleEdit(index, row) {
      this.title = '修改员工'
      this.employee = row
      this.dialogFormVisible = true

      console.log(index, row);
    },

    handleDelete(index, row) {
      this.eids = []
      if (row) {
        this.eids.push(row.eid)
      } else {
        this.eids = this.multipleSelection.map(m => m.eid)
      }
      this.$confirm(`是否真的要删除工号为${this.eids}的员工吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        employeeApi.deleteemployee(this.eids)
            .then(({data: res}) => {
              console.log("res:", res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style>

#app {
  display: flex;
  justify-content: center;
}

.el-card {
  width: 90%;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
